// pages/formPowerOn/formPowerOn.js
import api from '../../utils/api'
let util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    approRole: '',
    userInfo: null,
    // 审批
    processList: [],
    disabled: false,
    // 申请信息
    keepLaunchDays: null,
    radioGroup: [
      {value: 1, name: '日常开机', checked: 'true'},
      {value: 2, name: '节假日开机'}
    ],
    startDate: util.formatTime(new Date()).split(' ')[0].replaceAll('/', '-'),
    startDateRange1: util.formatTime(new Date()).split(' ')[0].replaceAll('/', '-'),
    startDateRange2: '',
    endDate: util.formatTime(new Date()).split(' ')[0].replaceAll('/', '-'),
    endDateRange1: util.formatTime(new Date()).split(' ')[0].replaceAll('/', '-'),
    endDateRange2: '',
    visitRsn: '',
    // 设备信息
    list: [],
    item: {
      deviceCode: '',
      seat: '',
      userName: ''
    },
    // 操作信息
    showDialog: false,
    dialogInfo: '',
    buttons: [],
    // 表单信息
    approveFlag: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    if (options.id) {
      // 查询详情
      this.setData({
        id: options.id,
        approRole: options.approRole
      })
      if (options.source) {
        wx.setStorage({
          data: options.source,
          key: 'source',
        })
      }
      this.getDetails()
    } else {
      // 没有表单id，新建
      let data = wx.getStorageSync('logindata').data
      let userInfo = {
        applyName: data.name,
        applyType: 4,
        branch: data.department,
        depName: data.departmentName,
        workno: data.workno,
        phone: data.mobile,
      }
      this.setData({
        userInfo
      })
      this.renew()
      this.getKeepLaunchDays()
    }
  },

  // 更新设备
  renew: function () {
    let list = JSON.parse(JSON.stringify(this.data.list))
    list.push(this.data.item)
    this.setData({
      list
    })
  },
  // 查询保持开机日常保持天数
  getKeepLaunchDays: function () {
    let _this = this
    wx.request({
      url: api.getKeepLaunchDays,
      method: "GET",
      success(res) {
        if (res.data.state == 1) {
          _this.setData({
            keepLaunchDays: res.data.data
          })
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },
  // 开机类型选择
  radioChange(e) {
    // console.log('radio发生change事件，携带value值为：', e.detail.value)
    const radioGroup = this.data.radioGroup
    for (let i = 0, len = radioGroup.length; i < len; ++i) {
      radioGroup[i].checked = radioGroup[i].value == e.detail.value
    }
    let startDate = '', startDateRange1 = util.formatTime(new Date()).split(' ')[0].replaceAll('/', '-'), startDateRange2 = '';
    let endDate = '', endDateRange1 = util.formatTime(new Date()).split(' ')[0].replaceAll('/', '-'), endDateRange2 = '';
    // let startDate = '', startDateRange1 = '', startDateRange2 = '';
    // let endDate = '', endDateRange1 = '', endDateRange2 = '';
    this.setData({
      radioGroup,
      startDate,
      startDateRange1,
      startDateRange2,
      endDate,
      endDateRange1,
      endDateRange2
    })
  },
  // 日期选择
  bindDateChange: function (e) {
    console.log(e.detail.value)
    let datetime = new Date(e.detail.value).getTime()
    let radioVal = this.data.radioGroup.filter(item => item.checked)[0].value
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.currentTarget.dataset.type == 'start') {
      this.setData({
        startDate: e.detail.value,
        endDateRange1: e.detail.value
      })
      if (radioVal == 1) {
        this.setData({
          endDateRange2: util.formatTime(new Date(datetime + (this.data.keepLaunchDays - 1) * 24 * 60 * 60 * 1000)).split(' ')[0].replaceAll('/', '-')
        })
      } else if (radioVal == 2) {
        if (this.data.endDate) {
          // 调接口判断是否在节假日
          this.checkHoliday()
        }
      }
    } else if (e.currentTarget.dataset.type == 'end') {
      this.setData({
        startDateRange2: e.detail.value,
        endDate: e.detail.value
      })
      if (radioVal == 1) {
        this.setData({
          startDateRange1: util.formatTime(new Date(datetime - (this.data.keepLaunchDays + 1) * 24 * 60 * 60 * 1000)).split(' ')[0].replaceAll('/', '-')
        })
      } else if (radioVal == 2) {
        if (this.data.endDate) {
          // 调接口判断是否在节假日
          this.checkHoliday()
        }
      }
    }
  },
  // 节假日校验
  checkHoliday: function () {
    let _this = this
    wx.request({
      url: api.checkHoliday + '?begin=' + this.data.startDate.replaceAll('-', '') + '&end=' + this.data.endDate.replaceAll('-', ''),
      method: "GET",
      success(res) {
        if (res.data.state == 1) {
          if (!res.data.data) {
            _this.setData({
              startDate: '',
              startDateRange1: util.formatTime(new Date()).split(' ')[0].replaceAll('/', '-'),
              startDateRange2: '',
              endDate: '',
              endDateRange1: util.formatTime(new Date()).split(' ')[0].replaceAll('/', '-'),
              endDateRange2: '',
              showDialog: true,
              dialogInfo: '开机保持时间超出了法定节假日！',
              buttons: [{text: '知道了', extClass: 'cancelBtn'}]
            })
          }
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },
  // 申请事由
  bindTextAreaInput: function (e) {
    this.setData({
      visitRsn: e.detail.value
    })
  },
  // 添加新设备
  bindAddItem: function () {
    this.renew()
  },
  bindKeyInput: function (e) {
    let list = JSON.parse(JSON.stringify(this.data.list))
    switch (e.currentTarget.dataset.num) {
      case '0':
        list[e.currentTarget.dataset.index].deviceCode = e.detail.value
        break;
      case '1':
        list[e.currentTarget.dataset.index].seat = e.detail.value
        break;
      case '2':
        list[e.currentTarget.dataset.index].userName = e.detail.value
        break;
    }
    this.setData({
      list
    })
  },
  // 删除设备
  bindDeleteItem: function (e) {
    let list = JSON.parse(JSON.stringify(this.data.list))
    list.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      list
    })
  },
  // 校验栏位
  validate: function () {
    if (!this.data.startDate || !this.data.endDate || !this.data.visitRsn) {
      return '申请信息不能为空！'
    }
    let list = JSON.parse(JSON.stringify(this.data.list))
    for (let i in list) {
      if (!list[i].deviceCode || !list[i].seat || !list[i].userName) {
        return '设备信息不能为空！'
      }
    }
    
    return 'finished'
  },
  // 提交申请 -- 申请人
  bindSubmit: function () {
    let content = this.validate ()
    if (content != 'finished') {
      wx.showModal({
        content: content,
        showCancel: false
      })
      return
    }
    // console.log('请求查询审批人接口')
    let _this = this
    wx.request({
      url: api.formGetNextApprover,
      method: "GET",
      data: {
        workno: _this.data.userInfo.workno,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.state == 1) {
          _this.setData({
            showDialog: true,
            dialogInfo: '下一步审批处理人：' + res.data.data.name,
            buttons: [{text: '返回', extClass: 'cancelBtn'}, {text: '知道了', extClass: 'dialogBtn'}]
          })
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },
  bindOperate: function (e) {
    console.log(e)
    let index = e.detail.index
    this.setData({
      showDialog: false
    })
    if (index == 1) {
      // 提交接口 -- 只有申请人调用，和保存一个接口，标志不一样
      this.bindSave('submit')
    } else if (index == 0) {
      if (e.detail.item.extClass == 'dialogBtn') {
        this.goBack()
      }
    }
  },
  bindSave: function (val) {
    let url = val == 'submit' ? api.formSubmitRequest : api.formSaveRequest
    let formData = JSON.parse(JSON.stringify(this.data.userInfo))
    formData.id = this.data.id
    formData.keepType = this.data.radioGroup.filter(item => item.checked)[0].value
    formData.visitRsn = this.data.visitRsn
    formData.startdate = this.data.startDate
    formData.enddate = this.data.endDate
    formData.keepLaunchList = this.data.list
    let _this = this
    wx.showLoading({
      title: '请稍候',
      mask: true
    })
    wx.request({
      url: url,
      method: "POST",
      data: formData,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        wx.hideLoading()
        if (res.data.state == 1) {
          wx.showToast({
            icon: 'success',
            title: val == 'submit' ? "提交成功" : "保存成功"
          })
          _this.goBack()
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },


  getDetails: function () {
    let _this = this
    wx.request({
      url: api.formRequestDetail + this.data.id,
      data: {
        workno: wx.getStorageSync("workNo")
      },
      method: "GET",
      success(res) {
        if (res.data.state == 1) {
          let data = res.data.data
          let processList = data.applyApproveList
          if (data.status < 5) {
            processList?.unshift(data.nextApproverInfo)
          }
          processList?.forEach(item => {
            switch (item.approRole) {
              case 'C':
                item.showName = '物业办理'
                break;
              case 'D':
                item.showName = '园区审批'
                break;
              case 'B':
                item.showName = '综合管理部审批'
                break;
              case 'A':
                item.showName = '部门审批'
                break;
              default:
                item.showName = '提交审批'
                break;
            }
            if (_this.data.approRole && (_this.data.approRole == item.approRole)) {
              item.showName = _this.data.approRole == data.approveNode ? '请您审批此申请' : '您已完成此审批'
            }
          })
          const radioGroup = _this.data.radioGroup
          for (let i = 0, len = radioGroup.length; i < len; ++i) {
            radioGroup[i].checked = radioGroup[i].value == data.keepType
          }
          _this.setData({
            userInfo: data,
            processList,
            disabled: data.status > 0 ? true : false,
            radioGroup,
            startDate: data.startdate.slice(0, 10),
            endDate: data.enddate.slice(0, 10),
            visitRsn: data.visitRsn,
            list: data.keepLaunchList,
            approveFlag: _this.data.approRole == data.approveNode ? false : true
          })
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },
  // 通过申请 -- 审批人
  bindApprove: function () {
    console.log('请求审批接口')
    let _this = this
    //显示等待框
    wx.showLoading({
      title: '请稍候',
      mask: true
    })
    wx.request({
      url: api.approve,
      method: "POST",
      data: {
        workNo: wx.getStorageSync("workNo"),
        applyId: this.data.id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        wx.hideLoading()
        if (res.data.state == 1) {
          _this.setData({
            showDialog: true,
            dialogInfo: '审批成功',
            buttons: [{text: '知道了', extClass: 'dialogBtn'}]
          })
        } else {
          wx.showToast({
            icon: "error",
            title: res.data.message,
          })
        }
      }
    })
  },
  // 退回申请
  bindReject: function () {
    let id = this.data.id
    wx.navigateTo({
      url: '/pages/formReject/formReject?requestId=' + id + '&javaFlag=true'
    })
  },

  goBack: function () {
    if (wx.getStorageSync('source')) {
      // console.log('公众号退回')
      wx.reLaunch({
        url: '/pages/formHome/formHome'
      })
      wx.removeStorageSync('source')
    } else {
      // console.log('正常流程退回')
      wx.navigateBack({
        delta: 1,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})